package com.rp.gmall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rp.common.utils.PageUtils;
import com.rp.common.utils.Query;

import com.rp.gmall.product.dao.CategoryDao;
import com.rp.gmall.product.entity.CategoryEntity;
import com.rp.gmall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //查询一级分类
        List<Object> collect = categoryEntities.stream().filter(item -> {
           return item.getParentCid() == 0;
        }).map(v -> {
            v.setChildren(getChildrens(v,categoryEntities));
            return v;
        }).sorted((item1,item2) ->{
            return (item1.getSort() == null ? 0:item1.getSort()) -(item2.getSort() == null ? 0: item2.getSort());
        }).collect(Collectors.toList());

        return categoryEntities;
    }


    @Override
    public void removeMenusByIds(List<Long> asList) {

        int i = baseMapper.deleteBatchIds(asList);

    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(item -> {
            return item.getParentCid() == root.getCatId();
        }).map(item -> {
            item.setChildren(getChildrens(item, categoryEntities));
            return item;
        }).sorted((item1, item2) -> {
            return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}